﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using HealthMonitor.Models;
using System.Collections.Specialized;

namespace HealthMonitor.Controllers
{
    public class HealthController : ApiController
    {
        private readonly HealthMonitorContext db = new HealthMonitorContext();
        // GET api/health
        public IEnumerable<Nvironment> Get()
        {
            return db.Environments.ToArray();
        }

        // GET api/health/5
        public IEnumerable<SiteInfo> Get(int id)
        {
            var env = db.Environments.Find(id);
            if (env == null)
                return null;
            var sites = db.Sites.Where(s => s.NvironmentID == id).ToArray();

            using (var c = new WebClient())
            {
                var q = sites
                    .Select(s =>
                    {
                        IEnumerable<KeyValuePair<string, string>> response;
                        try
                        {
                            var reqResult = c.DownloadString(s.Uri);
                            var items= c.ResponseHeaders.AllKeys.Select(k =>new KeyValuePair<string, string>(k, c.ResponseHeaders[k]));
                            response = items;
                        }
                        catch (WebException wex)
                        {
                            response = new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>(wex.Message, wex.ToString()) }; 

                        }


                        return new SiteInfo(s,response);
                    }).ToArray();

                return q;
            }
        }

    }
}
